using System;
using Autofac;
using AutoMapper;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using netCoreStudy.Extensions;
using netCoreStudy.Helper;
using netCoreStudy.Middle;
using Newtonsoft.Json;
using Serilog;

namespace netCoreStudy
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		private const string
			CorsOrigins = "_myAllowSpecificOrigins"; // 定义 跨域

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddSingleton(new AppSettingHelper(Configuration));
			services.AddControllers()
				.AddFluentValidation()
				.AddNewtonsoftJson(options =>
				{
					//装 newtonsoft.json 包 和  aspnetcore.mvc.newtonsoftJson 包
					//将 json 解析换成 牛顿  的json 解析， 默认自带的 json解析 有问题…… ,这个 可以忽略 循环 引用 
					options.SerializerSettings.ReferenceLoopHandling =
						ReferenceLoopHandling.Ignore;
				});
			//添加AutoMapper
			services.AddAutoMapper(AppDomain.CurrentDomain
				.GetAssemblies());
			services.AddMemoryCache();
			services.AddDbSetup(Configuration);
			services.AddSwaggerSetup();
			services.AddValidatorSetup();
			services.AddQuartZSetup();
			services.AddCorsSetup(CorsOrigins); // 跨域
			services.AddAuthorizeSetup();
			// 对http上下文进行依赖注入
			services
				.AddSingleton<IHttpContextAccessor,
					HttpContextAccessor>();
		}

		public void ConfigureContainer(
			ContainerBuilder containerBuilder)
		{
			containerBuilder.RegisterModule<CustomAutofacModule>();
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
		{
			// 让程序启动时执行迁移 
			using var scope = app.ApplicationServices
				.GetService<IServiceScopeFactory>().CreateScope();
			var myDbContext = scope.ServiceProvider
				.GetRequiredService<ApiDbContext>();

			if (!myDbContext.Database.CanConnect()) // 检查db 是否存在 
			{
				logger.LogInformation(@"未找到数据库,将执行数据库迁移");
				myDbContext.Database.EnsureCreated();
			}
			else
			{
				logger.LogInformation(@"数据库已经存在");
			}


			if (env.IsDevelopment())

			{
				app.UseDeveloperExceptionPage();
			}

			app.UseStaticFiles();
			app.UseCors(CorsOrigins);
			// 精简一些日志 
			app.UseSerilogRequestLogging();
			//自己定义 的 swagger 中间件
			app.UseSwaggerMiddle();
			app.UseRouting();

			// 先开启认证
			app.UseAuthentication();
			// 然后是授权中间件
			app.UseAuthorization();
			// 自定义异常中间件,放到最后  开发的时候 先注释
			// app.UseErrorHandling();

			app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
		}
	}
}